<template>
  <div class="afterInvest-add-page app-container">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="submitHandle()" label-width="160px">
      <el-form-item prop="groupName" label="所属分组：">
        <el-input v-model="dataForm.groupName" placeholder="请选择投资分组" clearable readonly style="width: 280px;">
          <el-button slot="append" icon="el-icon-search" @click="combinationHandle"></el-button>
        </el-input>
      </el-form-item>
      <el-form-item prop="investName" label="投资名称：">
        <el-input v-model="dataForm.investName" placeholder="请输入投资名称" style="width: 280px;"></el-input>
      </el-form-item>
      <el-form-item prop="investType" label="投资形式：">
        <el-select v-model="dataForm.investType" placeholder="请选择投资形式" :disabled="dataForm.investId ? true : false" style="width: 280px;">
          <el-option :label="item.name" :value="item.id" v-for="item in typeList" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="investIndex" label="对标指数：">
        <indexSelectTree :multiple="false" v-model="dataForm.investIndex"></indexSelectTree>
      </el-form-item>
      <!-- <el-form-item prop="investIncomeRate" label="收益率：">
        <el-input v-model="dataForm.investIncomeRate" placeholder="请输入收益率" style="width: 280px;"></el-input>
      </el-form-item> -->
      <el-form-item prop="investMoney" label="投资金额(万元)：">
        <el-input-number v-model="dataForm.investMoney" placeholder="请输入投资金额" :disabled="dataForm.investCmfccAccountDtos.length?true:false" :controls="false" :precision="2" style="width: 160px;"></el-input-number>
      </el-form-item>
      <el-switch style="display: block;margin: 0 0 22px 160px;" v-model="switchType" @change="switchTypeChange" active-color="#409eff" inactive-color="#409eff" active-text="关联子账号" inactive-text="关联投顾"></el-switch>
      <el-form-item v-show="!switchType" prop="investAdviser" label="关联投顾：">
        <el-input v-model="dataForm.investAdviser" placeholder="请选择投顾" clearable readonly style="width: 280px;">
          <el-button slot="append" icon="el-icon-search" @click="selectHandle"></el-button>
        </el-input>
      </el-form-item>
      <el-form-item v-show="switchType" prop="investAccount" label="关联子账号：">
        <el-select v-model="dataForm.investAccount" filterable default-first-option clearable placeholder="请选择子账号" style="width: 280px;">
          <el-option
            v-for="item in subAccountList"
            :key="item.value"
            :label="item.username"
            :value="item.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="投资时间：" prop="investTime">
        <el-date-picker
          :disabled="dataForm.investId ? true : false"
          v-model="dataForm.investTime"
          type="date"
          value-format="timestamp"
          style="width: 280px;"
          placeholder="开始日期">
        </el-date-picker>
      </el-form-item>

      <el-button type="danger" size="small" style="margin-bottom: 22px;" @click="addHandle">添加期货账号</el-button>
      <!-- <div class="card" v-for="(item, i) in dataForm.investCmfccAccountDtos" :key="item.id"> -->
      <div class="card" v-for="(item, i) in investCmfccAccountList" :key="item.id">
        <div class="card-tit">
          <span>账号{{i+1}}：</span>
          <span class="close" @click="closeCardHandle(i)">X</span>
        </div>
        <el-form-item :prop="`investCmfccAccountDtos.${i}.investAccount`" label="期货账户：" :rules="dataRule.investAccount1">
          <el-input v-model="item.investAccount" placeholder="请输入期货账户" style="width: 280px;"></el-input>
        </el-form-item>
        <el-form-item :prop="`investCmfccAccountDtos.${i}.investPasswd`" label="账号密码：" :rules="dataRule.investPasswd">
          <el-input type="password" v-model="item.investPasswd" placeholder="请输入账号密码" style="width: 280px;"></el-input>
        </el-form-item>
        <el-form-item :prop="`investCmfccAccountDtos.${i}.investPasswd2`" label="确认密码：" :rules="dataRule.investPasswd2">
          <el-input type="password" v-model="item.investPasswd2" placeholder="请输入账号密码" style="width: 280px;"></el-input>
        </el-form-item>
        <el-form-item :prop="`investCmfccAccountDtos.${i}.initEquity`" label="初始金额(万元)：" :rules="dataRule.initEquity">
          <el-input-number v-model="item.initEquity" placeholder="请输入初始金额" @input="initEquityInputHandle" :controls="false" :precision="2" style="width: 160px;"></el-input-number>
        </el-form-item>
      </div>
    </el-form>
    
    <div class="footer">
      <el-button style="width: 220px;" type="primary" @click="submitHandle()">提交</el-button>
    </div>

    <investManageOpen v-if="selectVisible" ref="investManageOpen" @selctInvestManage="selctInvestManage"></investManageOpen>
    <addCombinationOpen v-if="addCombinationVisible" ref="addCombinationOpen" @selctCombination="selctCombination"></addCombinationOpen>
    
    <div style="height: 800px;"></div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { addInsertManage, updateManage, queryById, listChildrenAccount } from '@/api/afterInvest'
import indexSelectTree from '@/components/investComn/indexSelectTree.vue'
import investManageOpen from '@/views/afterManage/afterInvest/investManageOpen.vue'
import addCombinationOpen from '@/views/afterManage/afterInvest/addCombinationOpen.vue'

export default {
  name: 'AfterInvestAdd',
  components: { indexSelectTree, investManageOpen, addCombinationOpen },
  data() {
    var validatorInvestPasswd2 = (rule, value, callback) => {
      const i = rule.field.split('.')[1]
      if(value === '') {
        callback(new Error('请再次输入密码'))
      } else if(value !== this.dataForm.investCmfccAccountDtos[i].investPasswd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      typeList: [
        { id: 1, name: 'MOM' },
        { id: 2, name: 'FOF' },
        { id: 3, name: '专户' },
        { id: 4, name: '其他' }
      ],
      dataForm: {
        groupId: '',
        groupName: '',
        investId: null,
        investName: '',
        investIndex: undefined,
        investType: 1,
        investTypeText: 'MOM',
        investAdviser: undefined,
        investManage: undefined,
        investTime: new Date().getTime(),
        investCmfccAccountDtos: []
      },
      switchType: false,
      selectVisible: false,
      subAccountList: [],
      dataRule: {
        investName: [{ required: true, message: '请输入投资名称', trigger: 'blur' }],
        investMoney: [{ required: true, message: '请输入投资金额', trigger: 'blur' }],
        createdby: [{ required: true, message: '请输入创建账号名称', trigger: 'blur' }],
        investAccount1: [{ required: true, message: '请输入期货账户', trigger: 'blur' }],
        investPasswd: [{ required: true, message: '请输入账号密码', trigger: 'blur' }],
        initEquity: [{ required: true, message: '请输入初始金额', trigger: 'blur' }],
        investPasswd2: [{ validator: validatorInvestPasswd2, required: true, trigger: 'blur' }]
      },
      addCombinationVisible: false,
    }
  },
  computed: {
    ...mapGetters(['userId']),
    investCmfccAccountList() {
      const res = []
      this.dataForm.investCmfccAccountDtos.map(item => {
        if(item.deleteFlag) {
          res.push(item)
        }
      })
      return res
    }
  },
  created() {
    this.dataForm.investId = this.$route.query.id
    this.dataForm.groupId = this.$route.query.groupId
    this.dataForm.groupName = this.$route.query.groupName
    if(this.dataForm.investId) this.queryById(this.dataForm.investId)
    this.listChildrenAccount()
  },
  methods: {
    initEquityInputHandle() {
      let res = 0
      this.dataForm.investCmfccAccountDtos.map(item => {
        if(item.deleteFlag) res += Number(item.initEquity||0) 
      })
      this.dataForm.investMoney = res
    },
    addHandle() {
      if(this.dataForm.investId) {
        this.dataForm.investCmfccAccountDtos.push({
          deleteFlag: 1,
          investAccount: '',
          investPasswd: '',
          investPasswd2: '',
          initEquity: undefined,
          investId: this.dataForm.investId
        })
      }else {
        this.dataForm.investCmfccAccountDtos.push({
          deleteFlag: 1,
          investAccount: '',
          investPasswd: '',
          investPasswd2: '',
          initEquity: undefined
        })
      }
    },
    closeCardHandle(i) {
      if(this.dataForm.investId) {
        if(this.dataForm.investCmfccAccountDtos[i].id) { // 区分是否为编辑时新增
          this.$confirm('确认删除？', '提示', {
            customClass: 'del-model',
            type: 'warning'
          }).then(() => {
            this.dataForm.investCmfccAccountDtos[i].deleteFlag = 0
            this.initEquityInputHandle()
          }).catch(() => {})
        }else {
          this.dataForm.investCmfccAccountDtos.splice(i, 1)
          this.initEquityInputHandle()
        }
      }else {
        this.dataForm.investCmfccAccountDtos.splice(i, 1)
        this.initEquityInputHandle()
      }
    },
    listChildrenAccount() {
      listChildrenAccount({
        username: this.userId+'',
        "pageCurrent": 1,
        "limit": 100
      }).then(res => {
        this.subAccountList = res.page.list
      })
    },
    switchTypeChange(val) {
      val ? this.dataForm.investAdviser=undefined : this.dataForm.investAccount=undefined
    },
    selctInvestManage(investName) {
      this.dataForm.investAdviser = investName
    },
    selctCombination(params) {
      this.dataForm.groupId = params.groupId
      this.dataForm.groupName = params.groupName
    },
    combinationHandle() {
      this.addCombinationVisible = true
      this.$nextTick(() => {
        this.$refs.addCombinationOpen.init()
      })
    },
    selectHandle() {
      this.selectVisible = true
      this.$nextTick(() => {
        this.$refs.investManageOpen.init()
      })
    },
    queryById(investId) {
      queryById({ investId }).then(res => {
        res.body.investTime = new Date(res.body.investTime).getTime()
        res.body.investCmfccAccountDtos.map(item => {
          item.investPasswd2 = item.investPasswd
        })
        this.dataForm = res.body
      })
    },
    submitHandle() {
      this.$refs['dataForm'].validate((valid) => {
        if(valid) {
          this.dataForm.investTypeText = this.typeList[this.dataForm.investType-1].name
          if(!this.dataForm.investId) {
            addInsertManage({ ...this.dataForm, createdby: this.userId }).then(res => {
              this.$store.dispatch("tagsView/delView", this.$route)
              this.$router.push({
                path: '/afterManage/afterInvest',
                query: {
                  refresh: new Date().getTime()
                }
              })
            })
          }else {
            updateManage({ ...this.dataForm, createdby: this.userId }).then(res => {
              this.$store.dispatch("tagsView/delView", this.$route)
              this.$router.push({
                path: '/afterManage/afterInvest',
                query: {
                  refresh: new Date().getTime()
                }
              })
            })
          }
        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.afterInvest-add-page {
  .line {
    display: flex;
    align-items: center;
  }
  .card {
    position: relative;
    border: 1px solid #ddd;
    & + .card { margin-top: 22px; }
    .card-tit {
      display: flex;
      justify-content: space-between;
      align-items: center;
      line-height: 34px;
      background: #eee;
      padding: 0 12px;
      font-weight: bold;
      margin-bottom: 22px;
      .close {
        width: 20px;
        line-height: 20px;
        text-align: center;
        background: #ff3300;
        color: #fff;
        border-radius: 50%;
        cursor: pointer;
      }
    }
  }
  .footer {
    margin-top: 40px;
    text-align: center;
  }
}
</style>

